package com.ning.weibo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;


/**
 * Created by LiuNing on 2017/6/20.
 */

public class LoginActivity extends Activity {

    private SsoHandler mSsoHandler = null;
    private AuthInfo mAuthInfo = null;
    private Button btn_login;
    private Button btn_close;
    private Oauth2AccessToken mAccessToken = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mAuthInfo = new AuthInfo(this, Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);

        mSsoHandler = new SsoHandler(LoginActivity.this, mAuthInfo);

        btn_login = (Button) findViewById(R.id.btn_login);
        btn_close = (Button) findViewById(R.id.btn_close);

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mSsoHandler.authorizeWeb(new WeiboAuthListener() {
                    @Override
                    public void onComplete(Bundle bundle) {
                        mAccessToken = Oauth2AccessToken.parseAccessToken(bundle);
                        if (mAccessToken.isSessionValid()) {
                            AccessTokenKeeper.writeAccessToken(LoginActivity.this, mAccessToken);
                        } else {
                            Toast.makeText(LoginActivity.this, "授权异常", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                    @Override
                    public void onWeiboException(WeiboException e) {

                    }

                    @Override
                    public void onCancel() {
                        Intent intent = new Intent(LoginActivity.this, ShareActivity.class);
                        startActivity(intent);
                    }
                });
            }
        });

        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });
    }
}
